package edu.mercer.sse.plainpdf;

import java.util.concurrent.ExecutionException;

import edu.mercer.sse.annotations.Fulfills;
import edu.mercer.sse.error.CriticalException;
import edu.mercer.sse.error.ErrorLoggingVisitor;

/**
 * Verify PDF is valid.<p>
 * 
 * Use file attributes and utility to verify PDF accessible and not corrupt.<p> 
 * 
 * Wrapper Facade pattern demonstration.<p>
 * 
 * @see Validation
 * 
 * @see FileInformation
 * 
 * @see UtilityNomenclature
 */

public class PDFValidator implements Validation<FileInformation>,
								  	 UtilityNomenclature
{
	/** 
	 * Name of this utility as defined in configuration. Required for use by 
	 * generic Utility if used with no-arg constructor.<p>
	 * 
	 * @see UtilityNomenclature
	 * @see Utility
	 */
	
	final String UTILITY_KEY = "PDFINFO";

	/**
	 * Generic utility instance.<p>
	 * 
	 * Appropriate configuration loaded using {@link #UTILITY_KEY} through 
	 * 	UtilityNomenclature methods.<p>
	 */
	
	private Utility<?> _pdfCheckUtil;
	
	
	@Fulfills("Validation")
	@Override
	public Boolean isValid(FileInformation pdfFile) 
	{	
		Boolean result = false;
		
		/* 
		 * file is not within range for size, or path length, is a directory, 
		 * device, or is unaccessible 
		 */
		
		if( !pdfFile.isAvailable() ) return result;
		
		_pdfCheckUtil = new Utility<>( this );
		
		_pdfCheckUtil.setCommandLineVarValue("FILE_IN", pdfFile.getLocation());
		
		/* command line arguments haven't been supplied; i.e., FILE_IN, etc. */
		
		if( !_pdfCheckUtil.isReady() ) return result;
	
		try
		{
			/* check return code within range for this utility */
			
			result = _pdfCheckUtil._rcRange.contains(
		
				_pdfCheckUtil.asyncInvoke().get().getReturnCode());
		
		}
		catch( final ExecutionException | InterruptedException err )
		{
			final CriticalException errWrapped = new CriticalException(
					"error running pdf validation utility: " + pdfFile);

			errWrapped.accept(new ErrorLoggingVisitor());

			throw errWrapped;
			
		}//try

		return result;
		
	}//method

	
	@Fulfills("UtilityNomenclature")
	@Override
	public String getUtilityKey() 
	{
		return UTILITY_KEY;
		
	}//method


}//class
